package com.xqboss.web.controller.system;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.xqboss.apps.constant.RedisKey;
import com.xqboss.apps.domain.consumer.ConsumerRealName;
import com.xqboss.apps.dto.punch.GetWebPunchRecordDto;
import com.xqboss.apps.dto.sys.SysUserDto;
import com.xqboss.apps.service.consumer.ConsumerInviteRecordService;
import com.xqboss.apps.service.consumer.ConsumerRealNameService;
import com.xqboss.apps.vo.consumer.ConsumerInviteRecordVo;
import com.xqboss.apps.vo.sys.SysUserVo;
import com.xqboss.apps.vo.sys.WebSysUserInfoVo;
import com.xqboss.common.annotation.Log;
import com.xqboss.common.core.controller.BaseController;
import com.xqboss.common.core.domain.AjaxResult;
import com.xqboss.common.core.domain.R;
import com.xqboss.common.core.domain.entity.SysDept;
import com.xqboss.common.core.domain.entity.SysRole;
import com.xqboss.common.core.domain.entity.SysUser;
import com.xqboss.common.core.page.TableDataInfo;
import com.xqboss.common.core.redis.RedisCache;
import com.xqboss.common.enums.BusinessType;
import com.xqboss.common.utils.SecurityUtils;
import com.xqboss.common.utils.StringUtils;
import com.xqboss.common.utils.poi.ExcelUtil;
import com.xqboss.system.service.ISysDeptService;
import com.xqboss.system.service.ISysPostService;
import com.xqboss.system.service.ISysRoleService;
import com.xqboss.system.service.ISysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotNull;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户信息
 *
 * @author Administrator
 */
@Api(tags = {"用户管理"})
@RestController
@RequestMapping("/system/user")
public class SysUserController extends BaseController {
    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private ISysDeptService deptService;

    @Autowired
    private ISysPostService postService;
    @Autowired
    private ConsumerRealNameService consumerRealNameService;
    @Autowired
    private ConsumerInviteRecordService consumerInviteRecordService;
    @Autowired
    private RedisCache redisCache;

    /**
     * 获取用户列表
     */
    @PreAuthorize("@ss.hasPermi('system:user:list')")
    @GetMapping("/list")
    public TableDataInfo list(SysUser user) {
        startPage();
        List<SysUser> list = userService.selectUserList(user);
        return getDataTable(list);
    }

    @Log(title = "用户管理", businessType = BusinessType.EXPORT)
    @PreAuthorize("@ss.hasPermi('system:user:export')")
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysUser user) {
        List<SysUser> list = userService.selectUserList(user);
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        util.exportExcel(response, list, "用户数据");
    }

    @Log(title = "用户管理", businessType = BusinessType.IMPORT)
    @PreAuthorize("@ss.hasPermi('system:user:import')")
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception {
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        List<SysUser> userList = util.importExcel(file.getInputStream());
        String operName = getUsername();
        String message = userService.importUser(userList, updateSupport, operName);
        return success(message);
    }

    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) {
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        util.importTemplateExcel(response, "用户数据");
    }

    /**
     * 根据用户编号获取详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:user:query')")
    @GetMapping(value = {"/", "/{userId}"})
    public AjaxResult getInfo(@PathVariable(value = "userId", required = false) Long userId) {
        userService.checkUserDataScope(userId);
        AjaxResult ajax = AjaxResult.success();
        List<SysRole> roles = roleService.selectRoleAll();
        ajax.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        ajax.put("posts", postService.selectPostAll());
        if (StringUtils.isNotNull(userId)) {
            SysUser sysUser = userService.selectUserById(userId);
            ajax.put(AjaxResult.DATA_TAG, sysUser);
            ajax.put("postIds", postService.selectPostListByUserId(userId));
            ajax.put("roleIds", sysUser.getRoles().stream().map(SysRole::getRoleId).collect(Collectors.toList()));
        }
        return ajax;
    }

    /**
     * 新增用户
     */
    @PreAuthorize("@ss.hasPermi('system:user:add')")
    @Log(title = "用户管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody SysUser user) {
        if (!userService.checkUserNameUnique(user)) {
            return error("新增用户'" + user.getUserName() + "'失败，登录账号已存在");
        } else if (StringUtils.isNotEmpty(user.getPhonenumber()) && !userService.checkPhoneUnique(user)) {
            return error("新增用户'" + user.getUserName() + "'失败，手机号码已存在");
        } else if (StringUtils.isNotEmpty(user.getEmail()) && !userService.checkEmailUnique(user)) {
            return error("新增用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        user.setUserId(IdUtil.getSnowflakeNextId());
        user.setCreateBy(getUsername());
        user.setUserType("00");
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        return toAjax(userService.insertUser(user));
    }

    /**
     * 修改用户
     */
    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody SysUser user) {
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getUserId());
        if (!userService.checkUserNameUnique(user)) {
            return error("修改用户'" + user.getUserName() + "'失败，登录账号已存在");
        } else if (StringUtils.isNotEmpty(user.getPhonenumber()) && !userService.checkPhoneUnique(user)) {
            return error("修改用户'" + user.getUserName() + "'失败，手机号码已存在");
        } else if (StringUtils.isNotEmpty(user.getEmail()) && !userService.checkEmailUnique(user)) {
            return error("修改用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        user.setUpdateBy(getUsername());
        return toAjax(userService.updateUser(user));
    }

    /**
     * 删除用户
     */
    @PreAuthorize("@ss.hasPermi('system:user:remove')")
    @Log(title = "用户管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{userIds}")
    public AjaxResult remove(@PathVariable Long[] userIds) {
        if (ArrayUtils.contains(userIds, getUserId())) {
            return error("当前用户不能删除");
        }
        return toAjax(userService.deleteUserByIds(userIds));
    }

    /**
     * 重置密码
     */
    @PreAuthorize("@ss.hasPermi('system:user:resetPwd')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/resetPwd")
    public AjaxResult resetPwd(@RequestBody SysUser user) {
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getUserId());
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        user.setUpdateBy(getUsername());
        return toAjax(userService.resetPwd(user));
    }

    /**
     * 状态修改
     */
    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @ApiOperation("状态修改")
    @PutMapping("/changeStatus")
    public AjaxResult changeStatus(@RequestBody SysUser user) {
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getUserId());
        user.setUpdateBy(getUsername());
        return toAjax(userService.updateUserStatus(user));
    }

    /**
     * 根据用户编号获取授权角色
     */
    @PreAuthorize("@ss.hasPermi('system:user:query')")
    @GetMapping("/authRole/{userId}")
    public AjaxResult authRole(@PathVariable("userId") Long userId) {
        AjaxResult ajax = AjaxResult.success();
        SysUser user = userService.selectUserById(userId);
        List<SysRole> roles = roleService.selectRolesByUserId(userId);
        ajax.put("user", user);
        ajax.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        return ajax;
    }

    /**
     * 用户授权角色
     */
    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @Log(title = "用户管理", businessType = BusinessType.GRANT)
    @PutMapping("/authRole")
    public AjaxResult insertAuthRole(Long userId, Long[] roleIds) {
        userService.checkUserDataScope(userId);
        userService.insertUserAuth(userId, roleIds);
        return success();
    }

    /**
     * 获取部门树列表
     */
    @PreAuthorize("@ss.hasPermi('system:user:list')")
    @GetMapping("/deptTree")
    public AjaxResult deptTree(SysDept dept) {
        return success(deptService.selectDeptTreeList(dept));
    }

    @PreAuthorize("@ss.hasPermi('system:user:list-page')")
    @ApiOperation("用户列表")
    @PostMapping("list-page")
    public R<List<SysUserVo>> listPage(@RequestBody SysUserDto dto) {
        dto.startPageAndOrder();
        List<SysUserVo> list = consumerRealNameService.findBy(dto);
        return R.ok(list);
    }

    @PreAuthorize("@ss.hasPermi('system:user:info')")
    @ApiOperation("根据主键查询详情")
    @GetMapping("/info/{userId}")
    public R<WebSysUserInfoVo> findByKey(@PathVariable("userId") Long userId) {
        return consumerRealNameService.findByKey(userId);
    }

    @PreAuthorize("@ss.hasPermi('system:user:delRealName')")
    @ApiOperation("删除实名")
    @Log(title = "实名", businessType = BusinessType.DELETE)
    @DeleteMapping("delRealName/{userId}")
    public R delRealName(@PathVariable("userId") Long userId) {
        LambdaUpdateWrapper<ConsumerRealName> wq = new LambdaUpdateWrapper<>();
        wq.eq(ConsumerRealName::getUserId, userId);
        consumerRealNameService.remove(wq);
        return R.ok();
    }

    @PreAuthorize("@ss.hasPermi('system:user:recommend-list')")
    @ApiOperation("推荐列表")
    @PostMapping("/recommend-list")
    public R<List<ConsumerInviteRecordVo>> recommendList(@RequestBody GetWebPunchRecordDto dto) {
        if (ObjUtil.isNull(dto.getUserId())) {
            return R.fail("参数错误");
        }
//        LambdaQueryWrapper<ConsumerInviteRecord> query = new LambdaQueryWrapper<>();
//        if (dto.getCreateTimeStart() != null) {
//            query.ge(ConsumerInviteRecord::getCreateTime, dto.getCreateTimeStart());
//        }
//        if (dto.getCreateTimeEnd() != null) {
//            query.le(ConsumerInviteRecord::getCreateTime, dto.getCreateTimeEnd());
//        }
//        query.eq(ConsumerInviteRecord::getInvitId, dto.getUserId());
        dto.startPageAndOrder();
        List<ConsumerInviteRecordVo> vo = consumerInviteRecordService.webRecordList(dto);
        return R.ok(vo);
    }

    @PreAuthorize("@ss.hasPermi('system:user:del-order-count')")
    @ApiOperation("清除锁单次数")
    @Log(title = "清除锁单次数" , businessType = BusinessType.DELETE)
    @DeleteMapping("del-order-count/{userId}")
    public R delOrderCount(@PathVariable("userId")
                           @ApiParam(value = "用户ID" , required = true)
                           @NotNull(message = "用户ID不能为空")
                           Long userId) {
        redisCache.deleteObject(RedisKey.KEY_ORDER_CANCEL_COUNT_BY_USER + userId);
        return R.ok();
    }

    /**
     * 后台注销用户
     * @return
     */
    @PreAuthorize("@ss.hasPermi('system:user:update-status')")
    @ApiOperation("后台-注销用户")
    @Log(title = "后台-注销用户", businessType = BusinessType.UPDATE)
    @DeleteMapping("/update-status")
    public R logOff(@RequestBody SysUser user) {
        user.setUpdateBy(getUsername());
        int i = userService.updateUserStatus(user);
        if (i != 1) {
            return R.fail("操作失败");
        }
        return R.ok();
    }
}
